package image

import (
	"crypto/md5"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"io/ioutil"
	"os"
	"smartLearn/imghand"
	"smartLearn/models"
	"smartLearn/modules/response"
)
type ImageInfo struct {
	Filename string
	Imgid   string
}

var imgPath = "img/"

func AddImage(c *gin.Context){
	//TODO:添加图片逻辑
	var list []ImageInfo
	//time.Sleep(5*time.Second)
	mForm,err:=c.MultipartForm()
	if err!=nil{
		response.ShowError(c,err.Error())
		return
	}
	fhs :=mForm.File["file"]
	//fhs := c.Request.MultipartForm.File["file"]
	for _, fheader := range fhs {
		file,err:=fheader.Open()

		imageInfo:=ImageInfo{}
		imageInfo.Filename=fheader.Filename
		if err!=nil{
			response.ShowError(c,err.Error())
			return
		}
		//print(fheader)
		md5Hash := md5.New()
		io.Copy(md5Hash, file)


		// 进行 MD5 算计，返回 16进制的 byte 数组
		fileMd5FX := md5Hash.Sum(nil)
		fileMd5 := fmt.Sprintf("%x", fileMd5FX)

		// 组合文件完整路径
		dirPath := imghand.JoinPath(fileMd5) + "/" // 目录
		filePath := dirPath + fileMd5              // 文件路径


		//c.SaveUploadedFile(fheader,filepath)
		// 获取目录信息，并创建目录
		dirInfo, err := os.Stat(dirPath)
		if err != nil {
			err = os.MkdirAll(dirPath, 0755)
			if err != nil {
				response.ShowError(c,err.Error())
				return
			}
		} else {
			if !dirInfo.IsDir() {
				err = os.MkdirAll(dirPath, 0755)
				if err != nil {
					response.ShowError(c,err.Error())
					return
				}
			}
		}

		err=c.SaveUploadedFile(fheader,filePath)
		if err!=nil{
			response.ShowError(c,err.Error())
			return
		}
		imageInfo.Imgid=fileMd5
		list=append(list, imageInfo)
	}
	var data = make(map[string]interface{}, 0)
	data["list"]=list
	response.ShowData(c,data)

}
func ShowImage(c *gin.Context){

	imgid:=c.Param("id")
	// 组合文件完整路径
	filePath := imghand.UrlParse(imgid)
	if filePath == "" {
		response.ShowError(c,"图片不存在")
		return
	}

	c.File(filePath)
}
func DeleteUseless(c *gin.Context){

	err:=removeDir(imgPath)
	if err!=nil{
		response.ShowError(c,err.Error())
		return
	}

	PthSep := string(os.PathSeparator)
	dir, _ := ioutil.ReadDir(imgPath)
	for _, fi := range dir {
		if fi.IsDir() {//判断是不是空目录
			subDirPath:=imgPath + PthSep + fi.Name()

			subdir, _ := ioutil.ReadDir(subDirPath)
			if len(subdir) == 0 {
				fmt.Println("remove ",subDirPath)
				err = os.Remove(subDirPath)
				if err!=nil{
					response.ShowError(c,err.Error())
					return
				}
			}


		}

	}
	response.ShowSuccess(c,"删除成功" )


}

func removeDir(dirPth string) error {
	dir, err := ioutil.ReadDir(dirPth)
	if err != nil {
		return err
	}
	PthSep := string(os.PathSeparator)
	// suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写

	for _, fi := range dir {

		if fi.IsDir() { // 忽略目录
			//files1 = append(files1, dirPth+PthSep+fi.Name())
			removeDir(dirPth + PthSep + fi.Name())
			fmt.Println(dirPth + PthSep + fi.Name())
		}else{
			systemQuestionImage:=models.SystemQuestionImage{}
			systemQuestionImage.ImgId=fi.Name()

			userQuestionImage:=models.UserAnswerImage{}
			userQuestionImage.ImgId=fi.Name()
			if (!systemQuestionImage.GetRowByImgId()) && (!userQuestionImage.GetRowByImgId()){
				fmt.Println("remove file :" + dirPth + PthSep + fi.Name())
				 err = os.Remove(dirPth + PthSep + fi.Name())

				if err != nil {
					return err
				}
			}

		}
	}
	return  nil

}

